import update from 'immutability-helper';
import { getModelList, getCookList, getCookData, getTimeInterval } from '../services/playback';

export default {

  namespace: 'playback',

  state: {
    models: [],
    cook_times: [],

    selectModel: '',
    detailData: [],
    firstFramePrefix: '',
    timeInterval: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *fetchModelList(_ , { call, put }) {
      const response = yield call(getModelList);
      yield put({
        type: 'save',
        payload: {
          key: 'models',
          value: response,
        }
      });
    },
    *fetchCookList({ payload: { model }}, { call, put }) {
      const response = yield call(getCookList, model);
      yield put({
        type: 'save',
        payload: {
          key: 'cook_times',
          value: response,
        }
      });
    },
    *fetchCookData({ payload: { model, time }}, { call, put }) {
      const response = yield call(getCookData, model, time);
      yield put({
        type: 'save',
        payload: {
          key: 'detailData',
          value: response,
        }
      });
      const firstFilename = response[0].filename;
      const index = firstFilename.lastIndexOf('_');
      const firstFramePrefix = firstFilename.substring(0, index);

      yield put({
        type: 'save',
        payload: {
          key: 'firstFramePrefix',
          value: firstFramePrefix,
        },
      });
    },
    *fetchTimeInterval({ payload: { model, time }}, { call, put }) {
      const response = yield call(getTimeInterval, model, time);
      yield put({
        type: 'save',
        payload: {
          key: 'timeInterval',
          value: response,
        }
      });
    },
  },

  reducers: {
    save(state, { payload : { key, value }}) {
      return update(state, { [key] : { $set: value}});
    },
  },

};
